package com.tronsis.distribution.activity.me.agent;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.RecruitBean;
import com.tronsis.distribution.bean.RegionBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.RecruitBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 招募代理
 */
public class AgentRecruitingActivity extends ToolBarBaseActivity {

    @BindView(R.id.rv_recruiting)
    RecyclerView mRv;

    private CommonAdapter<RecruitBean> mAdapter;
    private List<RecruitBean> mDataList = new ArrayList<>();
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private ClipboardManager myClipboard;

    private LoadMoreWrapper mLoadMoreWrapper;
    private AlertDialog mRegionDialog;
    private AlertDialog mCodeDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agent_recruiting);
        setTitle(true, getString(R.string.agent_recruiting), getString(R.string.my_recruiting));

        initRv();
        getRecruit(mPage, mSize, true);
        myClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        if (paramId == RIGHT_TEXT) {
            startActivity(new Intent(mContext, MyAgentRecruitingActivity.class));
        }
    }


    private void initRv() {
        mAdapter = new CommonAdapter<RecruitBean>(mContext, mDataList, R.layout.item_agent_recruiting) {
            @Override
            protected void convert(ViewHolder holder, RecruitBean recruitBean, final int position) {
                if (StringUtil.isEquals(recruitBean.getRole(), StateUtil.ROLE_AGENT)) {
                    holder.setText(R.id.tv_role, "招募代理了！");
                    holder.setVisible(R.id.tv_limit_label, false);
                    holder.setVisible(R.id.tv_limit, false);
                } else if (StringUtil.isEquals(recruitBean.getRole(), StateUtil.ROLE_UO_AGENT)) {
                    holder.setText(R.id.tv_role, "招募准代理了！");
                    holder.setVisible(R.id.tv_limit_label, false);
                    holder.setVisible(R.id.tv_limit, false);
                }
                if(recruitBean.isUnited()){
                    holder.setText(R.id.tv_level, "联创");
                }else{
                    holder.setText(R.id.tv_level, StateUtil.getLevelText(recruitBean.getLevel()));
                }
                holder.setText(R.id.tv_limit, recruitBean.getLimit() + "人");
                holder.setText(R.id.tv_createdOn, DateUtil.getDateTimeString(recruitBean.getCreatedOn()));

                holder.getView(R.id.tv_recruiting).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showQueryDialog(mDataList.get(position));

                    }
                });
            }
        };

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    getRecruit(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRv.addItemDecoration(decoration);
        mRv.setLayoutManager(new LinearLayoutManager(mContext));
        mRv.setAdapter(mLoadMoreWrapper);
    }

    int mode = 0;//选择模式，默认：0，两级：1

    private void showQueryDialog(final RecruitBean recruitBean) {
        mode = 0;
        UserBean loginUser = UserBizFactory.createBiz().getLoginUser(mContext);
        String userRegion = loginUser.getRegion();
        String userLevel = loginUser.getLevel();

        String level = recruitBean.getLevel();
        if (userRegion == null) {
            return;
        }
        final RegionBean regionBean;
        switch (level) {
            case "B":
                regionBean = new RegionBean();
                RegionBean provinceRegion = CommonUtil.getProvinceRegion(userRegion);
                List<RegionBean> children = new ArrayList<>();
                children.add(provinceRegion);
                regionBean.setChildren(children);
                break;
            case "C":
                if (StringUtil.isEquals(userLevel, "C")) {
                    //同级
                    regionBean = new RegionBean();
                    if (userRegion.length() >= 4) {
                        userRegion = userRegion.substring(0, 4);
                    }
                    RegionBean cityRegion = CommonUtil.getCityRegion(userRegion);
                    List<RegionBean> children2 = new ArrayList<>();
                    children2.add(cityRegion);
                    regionBean.setChildren(children2);
                } else {
                    if (userRegion.length() >= 2) {
                        userRegion = userRegion.substring(0, 2);
                    }
                    regionBean = CommonUtil.getProvinceRegion(userRegion);
                }
                break;
            case "D":
            case "E":
                if (StringUtil.isEquals(userLevel, "B")) {
                    if (userRegion.length() >= 2) {
                        userRegion = userRegion.substring(0, 2);
                    }
                    mode = 1;
                    regionBean = CommonUtil.getProvinceRegion(userRegion);
                } else {
                    if (StringUtil.isEquals(userLevel, level)) {
                        regionBean = new RegionBean();
                        RegionBean cityRegion = CommonUtil.getCountryRegion(userRegion);
                        List<RegionBean> children2 = new ArrayList<>();
                        children2.add(cityRegion);
                        regionBean.setChildren(children2);
                    } else {
                        if (userRegion.length() >= 4) {
                            userRegion = userRegion.substring(0, 4);
                        }
                        regionBean = CommonUtil.getCityRegion(userRegion);
                    }

                }

                break;
            default:
                return;
        }
        if (regionBean == null) {
            ToastUtil.showMessage(mContext, "App 出错");
            return;
        }
        LogUtil.i("regionBean", regionBean.toString());
        final List<String> list = new ArrayList<>();
        final List<RegionBean> regionBeanList = new ArrayList<>(regionBean.getChildren());
        for (RegionBean bean : regionBeanList) {
            list.add(bean.getName());
        }

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_region, null);
        mRegionDialog = new AlertDialog.Builder(this).setView(view).create();


        final Spinner mSpinnerFactoryNum = (Spinner) view.findViewById(R.id.spinner_region);
        Button btnOk = view.findViewById(R.id.btn_confirm);

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.layout_textview_13);
        adapter.clear();
        adapter.add("请选择");
        adapter.addAll(list);
        mSpinnerFactoryNum.setAdapter(adapter);
        mSpinnerFactoryNum.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mode == 0) {
                    return;
                }

                if (position == 0) {
                    return;
                }

                if (mode == 1) {
                    mode = 0;
                    RegionBean selectRegion = regionBeanList.get(position - 1);
                    adapter.clear();
                    final List<String> list = new ArrayList<>();
                    final List<RegionBean> regionSecondnList = new ArrayList<>(selectRegion.getChildren());
                    regionBeanList.clear();
                    regionBeanList.addAll(regionSecondnList);
                    for (RegionBean bean : regionSecondnList) {
                        list.add(bean.getName());
                    }
                    adapter.add("请选择");
                    adapter.addAll(list);
                    adapter.notifyDataSetChanged();
                    mSpinnerFactoryNum.setSelection(0);
                    mSpinnerFactoryNum.performClick();
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        ImageButton imbClose = view.findViewById(R.id.mbt_close);
        imbClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRegionDialog.dismiss();
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String select = mSpinnerFactoryNum.getSelectedItem().toString();
                if (StringUtil.isEquals("请选择", select)) {
                    ToastUtil.showMessage(mContext, "请选择归属地");
                    return;
                }

                String region = null;
                for (RegionBean bean : regionBeanList) {
                    if (bean.getName().equals(select)) {
                        region = bean.getCode();
                        break;
                    }
                }
                mRegionDialog.dismiss();
                if (region.length() < 6) {
                    StringBuilder regionBuilder = new StringBuilder(region);
                    for (int i = 0; i < (6 - region.length()); i++) {
                        regionBuilder.append("0");
                    }
                    region = regionBuilder.toString();
                }
                httpGetCode(region, recruitBean);
            }
        });
        mRegionDialog.show();

        mRegionDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                adapter.clear();
                mRegionDialog = null;
            }
        });
    }


    private void showCodeDialog(String code) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_code, null);
        mCodeDialog = new AlertDialog.Builder(this).setView(view).create();
        final TextView tv = view.findViewById(R.id.tv_code);
        tv.setText(code);

        ImageButton imbClose = view.findViewById(R.id.mbt_close);
        imbClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeDialog.dismiss();
            }
        });

        Button btnCopy = view.findViewById(R.id.btn_copy);
        btnCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showMessage(mContext, "复制成功");
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("", tv.getText().toString());
                // 将ClipData内容放到系统剪贴板里。
                myClipboard.setPrimaryClip(mClipData);
                mCodeDialog.dismiss();
            }
        });

        Button btnCancel = view.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeDialog.dismiss();
            }
        });

        mCodeDialog.show();
    }

    private void httpGetCode(String region, RecruitBean recruitBean) {
        try {
            RecruitBizFactory.createBiz().getRecruitCode(AgentRecruitingActivity.this, recruitBean.getId(), region, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    String code = (String) data;
                    showCodeDialog(code);
                    dismissLoadingDialog();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


    private void getRecruit(int page, int size, final boolean isRefresh) {
        try {
            RecruitBizFactory.createBiz().getRecruit(this, page, size, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<RecruitBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

